package com.logansoft.zhxypkoa.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.logansoft.zhxypkoa.components.JwtToken;
import com.logansoft.zhxypkoa.components.JwtTool;
import com.logansoft.zhxypkoa.components.JwtUser;
import com.logansoft.zhxypkoa.domain.sys.User;
import com.logansoft.zhxypkoa.repository.sys.UserRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class AuthController {

	private UserRepository userRepository;
	private JwtTool jwtTool;

	@Autowired
	public AuthController(UserRepository userRepository, JwtTool jwtTool) {
		// TODO Auto-generated constructor stub
		this.userRepository = userRepository;
		this.jwtTool = jwtTool;
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ResponseEntity<?> login(@Validated @RequestBody User user) {
		log.debug("user.username: " + user.getUsername());
		User findUser = this.userRepository.findByUsernameAndPassword(user.getUsername(),
				DigestUtils.md5Hex(user.getOrgPassword()));
		String token = this.jwtTool
				.generateToken(new JwtUser(findUser.getId(), findUser.getUsername(), findUser.getCreatedAt()));
		return ResponseEntity.ok(new JwtToken(token, findUser.getId()));
	}

	@RequestMapping(value = "/login2", method = RequestMethod.POST)
	public ResponseEntity<?> login(@Param(value = "username") String username,
			@Param(value = "password") String passowrd) {
		log.debug("username: " + username);
		User findUser = this.userRepository.findByUsernameAndPassword(username, DigestUtils.md5Hex(passowrd));
		return ResponseEntity.ok(findUser);
	}
}
